package com.mantru.iotpot.job;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.eventbus.EventMessage;

import org.greenrobot.eventbus.EventBus;

import java.io.*;
import java.text.*;
import java.util.*;

public class TimerTriggerThread extends Thread
{
	private ApplicationClass ac;
	private int timer_interval;     //触发器的时间
	private int function_code;      //触发后的动作，0x03读、0x06写
	private int register_address;   //触发后的寄存器地址
	private int output_value;       //触发后要写入的值
	private int timer_pass;

	public TimerTriggerThread(ApplicationClass ac, int timer_interval, int function_code, int register_address, int output_value)
	{
		this.ac = ac;
		this.timer_interval = timer_interval;
		this.function_code = function_code;
		this.register_address = register_address;
		this.output_value = output_value;
		timer_pass = 0;
	}

	@Override
	public void run()
	{
		int sleep_interval = 50;
		try{
			//定时睡眠
			while(timer_pass < timer_interval){
				Thread.sleep(sleep_interval);
				timer_pass += sleep_interval;
				if (ac.job == null || ac.job.job_status == JobMaster.JOB_STATUS_STOP)
					return;
			}
			//填写参数
			String json_data = "{\"timer_interval\":\""+timer_interval+"\", \"function_code\":\""+function_code+"\", \"register_address\":\""+register_address+"\", \"output_value\":\""+output_value+"\"}";
			//触发事件
			String msg = "{\"data\":\""+json_data+"\"}";
			EventMessage e = new EventMessage(EventMessage.MSG_ID_OnTrigger, msg);
			EventBus.getDefault().post(e);
		}catch(Exception e)
		{}
		// this.stop();
	}

}
